"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统内部使用工具
Case Name   : 主机间ssh失败执行pssh命令
Create At   : 2022/4/24
@zou_jialiang0501129488
Description :
    1.清除待操作主机间root互信
    2.执行pssh命令
    3.无需清理环境
Expect      :
    1.清理成功
    2.执行失败
    3.无需清理环境
History     :
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.Common import CommonSH
from testcase.utils.Logger import Logger
from yat.test import Node

primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2不执行')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_root_node = Node('PrimaryRoot')
        self.s_root_node1 = Node('Standby1Root')
        self.s_root_node2 = Node('Standby2Root')
        self.com_root = CommonSH("PrimaryRoot")
        self.common = Common()
        self.ssh_file = os.path.join('~', '.ssh', '*')

    def test_pssh(self):
        text = '-----step1:清除待操作主机间root互信; expect:成功-----'
        self.log.info(text)
        del_cmd = f'rm -rf {self.ssh_file}'
        self.log.info(del_cmd)
        del_res = self.common.get_sh_result(self.primary_root_node, del_cmd)
        self.assertEqual('', del_res, '互信删除失败')
        del_res = self.common.get_sh_result(self.s_root_node1, del_cmd)
        self.assertEqual('', del_res, '互信删除失败')
        del_res = self.common.get_sh_result(self.s_root_node2, del_cmd)
        self.assertEqual('', del_res, '互信删除失败')

        text = '-----step2:执行pssh -H {nodename} {正确源文件} {目标目录}; expect:失败-----'
        self.log.info(text)
        test = '-----查看主机名-----'
        self.log.info(test)
        node_name = self.common.get_sh_result(self.s_root_node1, "uname -n")
        self.assertIsNotNone(node_name, '执行失败:' + text)
        self.log.info('-----执行pssh命令-----')
        pssh_cmd = f"pssh -H {node_name} hostname"
        self.log.info(pssh_cmd)
        pssh_res = self.common.get_sh_result(self.primary_root_node, pssh_cmd)
        self.assertIn('Exited with error code 255', pssh_res, '执行失败')

    def tearDown(self):
        self.log.info('-----No Need To Clean-----')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
